const { links, link_category, blog_user } = require('@/model');

class LinkService {
  async getLinks({ pageSize, pageIndex, ...params }) {
    const offset = pageSize && pageIndex ? (pageIndex - 1) * pageSize : undefined;
    // console.log('params', params, 'pageSize:', pageSize, 'offset:', offset);
    const query = {
      where: {
        ...params
      },
      limit: pageSize,
      offset,
      include: [
        { model: link_category, 
          where: params?.category_id?{id: params?.category_id}:{},
          as: 'linkGroup' },
        { model: blog_user, as: 'creator', attributes: ['id', 'nickname',"username"] }
      ],
      order: [['order', 'ASC']]
    };

    const res = await links.findAndCountAll(query);
    return {
      total: res.count,
      list: res.rows.map(row => row.toJSON())
    };
  }

  async getAllLinks() {
    const res = await links.findAll({
      include: [
        { model: link_category, as: 'linkGroup' },
        { model: blog_user, as: 'creator', attributes: ['id', 'nickname'] }
      ],
      order: [['order', 'ASC']]
    });
    return res.map(row => row.toJSON());
  }

  async getCategoryWithLinks() {
    const categories = await link_category.findAll({
      order: [['order', 'ASC']],
      include: [{
        model: links,
        as: 'links',
        order: [['order', 'ASC']]
      }]
    });
    return categories.map(cat => {
      const catData = cat.get({ plain: true });
      return {
        ...catData,
        links: catData.links || []
      };
    });
  }

  async saveLink(data) {
    return await links.upsert(data);
  }

  async deleteLink(id) {
    return await links.destroy({ where: { id } });
  }
}

module.exports = new LinkService();